using Artizan.Iot.Hub.Mqtt.HttpApi.Host;
using Artizan.Iot.Hub.Mqtt.Server.Options;
using MQTTnet.AspNetCore;
using Serilog;
using Serilog.Events;

namespace AbpManual.IotHub;

public class Program
{
    public async static Task<int> Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
#if DEBUG
            .MinimumLevel.Debug()
#else
            .MinimumLevel.Information()
#endif
            .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
            .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
            .Enrich.FromLogContext()
            .WriteTo.Async(c => c.File("Logs/logs.txt"))
            .WriteTo.Async(c => c.Console())
            .CreateLogger();

        try
        {
            Log.Information("Starting Artizan-IotHub HttpApi Host.");
            var builder = WebApplication.CreateBuilder(args);
            builder.Host.AddAppSettingsSecretsJson()
                .UseAutofac()
                .UseSerilog();

            /*-------------------------------------------------------------------------------------------
             * fix bug: 部署到 IIS 后, Mqtt client 无法连接 Mqtt server(broker) 
             * see:https://github.com/dotnet/MQTTnet/issues/1471
             */
            builder.WebHost.UseIIS();
            /*-------------------------------------------------------------------------------------------*/

            //builder.WebHost.ConfigureKestrel(serverOptions =>
            //{
            //    var iotHubMqttServerOptions = builder.Configuration.GetSection("IotHubMqttServer").Get<IotHubMqttServerOptions>();

            //    // This will allow MQTT connections based on TCP port xxxx .
            //    serverOptions.ListenAnyIP(port: iotHubMqttServerOptions.Port, opts => opts.UseMqtt());

            //    // This will allow MQTT connections based on HTTP WebSockets with URI "localhost:xxxx/mqtt"
            //    // See code below for URI configuration.
            //    serverOptions.ListenAnyIP(iotHubMqttServerOptions.WebSocketPort); // Default HTTP pipeline
            //});

            await builder.AddApplicationAsync<ArtizanIotHubMqttHttpApiHostModule>();
            var app = builder.Build();
            await app.InitializeApplicationAsync();
            await app.RunAsync();
            return 0;
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "Host terminated unexpectedly!");
            return 1;
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }
}
